package com.zhouzj.task.springcloud.code.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.zhouzj.task.springcloud.code.domain.LagouAuthCode;
import com.zhouzj.task.springcloud.code.repo.LagouAuthCodeRepo;
import com.zhouzj.task.springcloud.email.api.EmailService;
import com.zhouzj.task.springcode.code.api.CodeService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: zhouzhijun
 * @Date: 2021/8/5 15:23
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Reference
    private EmailService emailService;

    @Resource
    private LagouAuthCodeRepo lagouAuthCodeRepo;

    @Override
    public Boolean send(String email) {
        DateTime now = DateUtil.date();
        Boolean repeatSend = lagouAuthCodeRepo.existsByEmailAndExpireTimeAfter(email, now);
        if (Boolean.TRUE.equals(repeatSend)) {
            List<LagouAuthCode> authCodes = lagouAuthCodeRepo.findByEmailAndExpireTimeAfter(email, now);
            authCodes.forEach(authCode -> {
                authCode.setExpireTime(now);
                lagouAuthCodeRepo.saveAndFlush(authCode);
            });
        }

        String code = RandomUtil.randomString(6);
        Boolean send = emailService.send(email, code);
        if (Boolean.TRUE.equals(send)) {
            LagouAuthCode authCode = new LagouAuthCode();
            authCode.setCode(code);
            authCode.setEmail(email);
            authCode.setCreateTime(now);
            authCode.setExpireTime(now.offsetNew(DateField.MINUTE, 10));
            lagouAuthCodeRepo.save(authCode);
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean check(String email, String code) {
        return lagouAuthCodeRepo.existsByEmailAndExpireTimeAfterAndCode(email, DateUtil.date(), code);
    }
}
